package com.csist.client;



import com.csist.message.FileMessage;
import java.io.*;
import java.net.Socket;
import java.util.ArrayList;

/**
 * @ClassName Client
 * @Description 服务器端上传文件
 * @Author User
 * @Date 2021/6/9 8:47
 * @ModifyDate 2021/6/9 8:47
 * @Version 1.0
 */
public class Client {
    public static void main(String[] args) {
        Socket socket = null;
        try {
            socket = new Socket("127.0.0.1",8888);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());

            String sendFilePath = "D:\\send";
            File file = new File(sendFilePath);
            if (file.exists())file.mkdirs();
            System.out.println("准备上传文件到服务器，请在"+sendFilePath+"准备需要上传的文件");

            File[] files = file.listFiles();
            if (files.length<1){
                System.out.println("无文件！请在"+sendFilePath+"文件夹里添加需要发送的文件");
                return;
            }
            System.out.println("已读取到文件，上传中...");

            ArrayList<FileMessage> fileMessages = new ArrayList<>();
            for (File f:files) {
                FileMessage fileMessage = getFileMessage(f.getAbsolutePath());
                fileMessages.add(fileMessage);
            }

            oos.writeObject(fileMessages);
            oos.flush();
            String  msg = new BufferedReader(new InputStreamReader(socket.getInputStream())).readLine();
            System.out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket!=null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("客户端已关闭");
        }
    }
    private static FileMessage getFileMessage(String path){
        FileMessage fileMessage = new FileMessage();
        File file = new File(path);
        String name = file.getName();
        String type = file.getName().substring(file.getName().lastIndexOf("."));
        Long size = file.length();

        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] bytes = new byte[Integer.parseInt(String.valueOf(size))];
            fis.read(bytes);
            fileMessage = new FileMessage(name,type,size,bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return fileMessage;
    }
}
